// pages/fb_add/fb_add.js
import tool from '../../modules/tool'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {
      content: '',
      role: 'student',
      image: '',
      campusId: null,
      categoryId: null,
      location1: null,
      location2: null,
      name: '',
      phone: '',
      departmentId: null,
      className: ''
    },
    isScanCode: true,
    contentEdited: false,
    showTip: false,
    recommendPersonalInfo: null,
    showIsDmtrQuestion: false
  },

  handleHideTip() {
    this.setData({
      showTip: false
    })
  },

  handleShowDmtrQuestionForm() {
    this.setData({
      showIsDmtrQuestion: true
    })
  },

  handleHideDmtrQuestionForm() {
    this.setData({
      showIsDmtrQuestion: false
    })
  },

  handleSubmitWithNoCheck() {
    this.submit(true)
  },

  handleSubmit() {
    this.submit(false)
  },

  async submit(noCheck = false) {
    let form = JSON.parse(JSON.stringify(this.data.form))
    await tool.flow(async () => {
      if (!form.content) throw '输入问题内容'
      if (!this.data.contentEdited) throw '在“描述您的事项”中继续输入您的问题'
      if (form.content.length > 32) throw '问题内容不能长于32个字符'
      if (!form.campusId) throw '选择校区'
      if (!form.categoryId) throw '选择类别'
      // 如果有可能是宿舍问题，就显示提示框
      const dmtrNames = ['宿舍', '紫藤', '群星', '学苑', '公寓']
      if (noCheck === false && (() => {
          for (let i = 0; i < dmtrNames.length; i++) {
            if (form.content.indexOf(dmtrNames[i]) !== -1) return true
          }
          return false
        })()) {
        this.handleShowDmtrQuestionForm()
        return
      }
      if (form.image) {
        form.image = await tool.compressImage(form.image)
        let re_upload = await tool.uploadFileToServer(form.image, true)
        try {
          re_upload = JSON.parse(re_upload)
        } catch (error) {

        }
        if (re_upload.status) {
          form.image = re_upload.data
        } else {
          throw re_upload.content
        }
      }
      form.openId = tool.store.getItem('openId')
      let re = await tool.requestData('/feedback/add', form)
      if (re.status) {
        wx.setStorageSync('fb_add_last', JSON.stringify(form))
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 500
        })
        await tool.wait(0.5)
        tool.refreshHomeData()
        wx.navigateBack()
        await tool.wait(0.3)
        tool.feedback.showDetailPage(re.data)
      } else {
        throw re.content
      }
    }, err => wx.showToast({
      title: `${err}`,
      icon: 'error',
      duration: 1000
    }))
  },

  inputName(e) {
    e = e.detail.value
    this.setData({
      form: this.changeAndGetForm(t => {
        t.name = e
        return t
      })
    })
  },

  inputPhone(e) {
    e = e.detail.value
    this.setData({
      form: this.changeAndGetForm(t => {
        t.phone = e
        return t
      })
    })
  },

  inputClassName(e) {
    e = e.detail.value
    this.setData({
      form: this.changeAndGetForm(t => {
        t.className = e
        return t
      })
    })
  },

  async selectDepartment() {
    if (this.data.form.departmentId !== null && await new Promise((resolve, reject) => {
        tool.handleShowActionSheet([{
            name: '删除',
            callBack: () => resolve(true)
          },
          {
            name: '重新选择',
            callBack: () => resolve(false)
          },
        ])
      })) {
      this.setData({
        form: this.changeAndGetForm(t => {
          delete t.departmentName
          t.departmentId = null
          return t
        })
      })
      return
    }
    tool.flow(async () => {
      let re_department = await tool.requestData('/user/getDepartmentList', {}, 'get')
      if (!re_department.status) throw re_department.content
      tool.handleShowFDSelectPage('选择部门', (() => {
        let re = []
        for (let i = 0; i < re_department.data.length; i++) {
          re.push({
            title: re_department.data[i].name,
            item: re_department.data[i],
            key: re_department.data[i].id
          })
        }
        return re
      })(), this.data.form.departmentId, (e) => {
        this.setData({
          form: this.changeAndGetForm(t => {
            t.departmentId = e.id
            t.departmentName = e.name
            return t
          })
        })
      })
    }, err => tool.handleShowToast(`${err}`, 'error'))
  },

  changePos() {
    const handleSelect = () => {
      wx.chooseLocation({
        latitude: parseFloat(this.data.form.location1),
        longitude: parseFloat(this.data.form.location2),
        success: (e) => {
          if (e.errMsg == 'chooseLocation:ok') {
            this.setData({
              form: this.changeAndGetForm(t => {
                t.location1 = `${e.latitude}`
                t.location2 = `${e.longitude}`
                return t
              })
            })
          } else {

          }
        },
        fail: (e) => console.log(e)
      })
    }
    if (this.data.form.location1 === null) {
      handleSelect()
    } else {
      tool.handleShowActionSheet([{
          name: '删除',
          callBack: () => this.setData({
            form: this.changeAndGetForm(t => {
              t.location1 = null
              t.location2 = null
              return t
            })
          })
        },
        {
          name: '重新选择',
          callBack: () => handleSelect()
        }
      ])
    }
  },

  selectCampus() {
    tool.flow(async () => {
      let re_campus = await tool.requestData('/campus/getList', {}, 'get')
      if (!re_campus.status) throw re_campus.content
      tool.handleShowFDSelectPage('选择校区', (() => {
        let re = []
        for (let i = 0; i < re_campus.data.default.length; i++) {
          re.push({
            title: re_campus.data.default[i].name,
            item: re_campus.data.default[i],
            key: re_campus.data.default[i].id
          })
        }
        return re
      })(), this.data.form.campusId, (e) => {
        this.setData({
          form: this.changeAndGetForm(t => {
            t.campusId = e.id
            t.campusName = e.name
            return t
          })
        })
      })
    }, err => tool.handleShowToast(`${err}`, 'error'))
  },

  selectCategory() {
    tool.flow(async () => {
      let re_category = await tool.requestData('/category/getList', {}, 'get')
      if (!re_category.status) throw re_category.content
      tool.handleShowFDSelectPage('选择类别', (() => {
        let re = []
        for (let i = 0; i < re_category.data.default.length; i++) {
          re.push({
            title: re_category.data.default[i].name,
            item: re_category.data.default[i],
            key: re_category.data.default[i].id
          })
        }
        return re
      })(), this.data.form.categoryId, (e) => {
        this.setData({
          form: this.changeAndGetForm(t => {
            t.categoryId = e.id
            t.categoryName = e.name
            return t
          })
        })
      })
    }, err => tool.handleShowToast(`${err}`, 'error'))
  },

  handleBack() {
    wx.navigateBack()
  },

  changeAndGetForm(callBack = () => {}) {
    let t = this.data.form
    t = callBack(t)
    return t
  },

  imageClick() {
    const handleSelect = () => {
      wx.chooseMedia({
        count: 1, // 只允许选择一个文件
        mediaType: ['image'], // 仅限图片
        sourceType: ['album', 'camera'], // 允许从相册或拍摄获取
        success: (res) => {
          this.setData({
            form: this.changeAndGetForm(t => {
              t.image = res.tempFiles[0].tempFilePath
              return t
            })
          })
        },
        fail(err) {
          // console.error('选择图片失败:', err);
        }
      });
    }
    if (this.data.form.image) {
      tool.handleShowActionSheet([{
          name: '预览',
          callBack: () => {
            wx.previewImage({
              urls: [this.data.form.image],
            })
          }
        },
        {
          name: '删除',
          callBack: () => this.setData({
            form: this.changeAndGetForm(t => {
              t.image = ''
              return t
            })
          })
        },
        {
          name: '替换',
          callBack: () => handleSelect()
        },
      ])
    } else {
      handleSelect()
    }
  },

  inputContent(e) {
    this.setData({
      form: this.changeAndGetForm(f => {
        f.content = e.detail.value
        return f
      }),
      contentEdited: true
    })
  },

  changeRoleToTeacher() {
    this.setData({
      form: (() => {
        let t = this.data.form
        t.role = 'teacher'
        return t
      })()
    })
  },

  changeRoleToStudent() {
    this.setData({
      form: (() => {
        let t = this.data.form
        t.role = 'student'
        return t
      })()
    })
  },

  handleUseLastPersonalInfo() {
    console.log(this.data.recommendPersonalInfo)
    const {
      name,
      phone,
      className,
      departmentId,
      departmentName
    } = this.data.recommendPersonalInfo
    this.setData({
      form: {
        ...this.data.form,
        ...{
          name,
          phone,
          className,
          departmentName,
          departmentId
        }
      }
    })
    this.setData({
      recommendPersonalInfo: null
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    tool.setPageData(this)
    let storeContent = tool.store.getItem('feedBack_add_autoFill_content')
    let storeCampusCategory = tool.store.getItem('feedBack_add_autoFill_campusCategory')
    tool.store.removeItem('feedBack_add_autoFill_content')
    tool.store.removeItem('feedBack_add_autoFill_campusCategory'); {
      let last = wx.getStorageSync('fb_add_last')
      if (last) {
        try {
          last = JSON.parse(last)
          this.setData({
            form: (() => {
              let form = this.data.form
              form.role = last.role
              return form
            })(),
            recommendPersonalInfo: (() => {
              const {
                name,
                phone,
                className,
                departmentId,
                departmentName
              } = last
              if (!name && !phone && !className && !departmentId && !departmentName) {
                return null
              }
              return {
                name,
                phone,
                className,
                departmentId,
                departmentName
              }
            })()
          })
        } catch (error) {

        }
      }
    }
    this.setData({
      form: this.changeAndGetForm(e => {
        if (storeContent) {
          e.content = storeContent
          this.setData({
            isScanCode: true
          })
        }
        if (storeCampusCategory) {
          e.campusId = storeCampusCategory.campusInfo.id
          e.categoryId = storeCampusCategory.categoryInfo.id
          e.campusName = storeCampusCategory.campusInfo.name
          e.categoryName = storeCampusCategory.categoryInfo.name
          this.setData({
            isScanCode: true
          })
        }
        return e
      })
    })
    if (this.data.isScanCode) {
      this.setData({
        showTip: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})